<?php
/**
 * 定义 Config 类
 * 
 * @copyright Copyright (c) 2008 Classic Reappear Technology LLC
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @version $Id: config.php 2009-2-27 下午02:21:19 蓝色身份 $
 */

/**
 * 系统配置类
 *
 * @author 蓝色身份 <lance.w@live.cn>
 * @copyright Copyright (c) 2008 Classic Reappear Technology LLC
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @package Config
 */
class Config extends ArrayObject
{
    /**
     * 构造函数
     *
     * @param mixed $arg
	 */
    public function __construct($arg = array())
    {
        if (empty($arg)) {
            throw new Exception('You must provide a non-empty value');
        }

        if (!is_array($arg)) {
            if (!is_file($arg)) {
                throw new Exception("File '$arg' does not exist or can't readable.");
            }
            $array = require_once $arg;
        } else {
            $array = $arg;
        }

        foreach ($array as &$value) {
        	if (is_array($value)) {
        		$value = new self($value);
        	}
        }

        parent::__construct($array);
    }

    /**
     * 魔术方法获取指定项的值
     *
     * @param string $name
     */
    public function __get($name)
    {
        return $this->offsetGet($name);
    }

    /**
     * 魔术方法设置指定项的值
     *
     * @param string $name
     * @param mixed $value
     */
    public function __set($name, $value)
    {
        $this->offsetSet($name, $value);
    }

    /**
     * 魔术方法判断指定项是否存在
     *
     * @param string $name
     * @return boolean
     */
    public function __isset($name)
    {
        return $this->offsetExists($name);
    }

    /**
     * 魔术方法卸载指定项
     *
     * @param string $name
     */
    public function __unset($name)
    {
        $this->offsetUnset($name);
    }

    /**
     * 转换成数组
     *
     * @return array
     */
    public function toArray()
    {
        $array = $this->getArrayCopy();
        foreach ($array as &$value) {
        	if ($value instanceof self) {
        		$value = $value->toArray();
        	}
        }
        return $array;
    }

    /**
     * 转换成字符串
     *
     * @return array
     */
    public function __toString()
    {
        return var_export($this->toArray(), true);
    }
}